# -*- coding: utf-8 -*-
from django.shortcuts import render,get_object_or_404, render_to_response
from django.http import HttpResponseRedirect,HttpResponse
from django.core.urlresolvers import reverse
from django.template import RequestContext, loader
from poudres.models import Poudre, Event, Type_Event
from commandes.forms import CommandeForm
from clients.models import Client
from commandes.models import Commande
from django.utils import simplejson 
import re, json   

def accueil_commande(request):
    return render_to_response('commandes/commande_accueil.html',
                              {'PAGE_TITLE': 'Quản lí đơn hàng' ,'WEBSITE_TITLE': 'DNTN Kiều Anh'})

def commande_index(request):
    liste_commandes = Commande.objects.select_related().all()
    return render_to_response('commandes/liste_commandes.html',
                              {'liste_commandes': liste_commandes,
                               'titre':"Liste đơn hàng đã nhập"},
                              context_instance=RequestContext(request))
def addcommande (request):
    if request.method == 'POST':
        """somme = request.POST['prix']*request.POST['quantite']
        if request.POST['autre1'] or request.POST['autre2'] or request.POST['autre3']:
            somme = somme + request.POST['autre1']+request.POST['autre2']+request.POST['autre3']
        request.POST['total'] = somme"""
        try:
            form = CommandeForm(request.POST)
            if form.is_valid():
                form.save()
                id_commande = form.instance.pk
                return HttpResponseRedirect('/commandes/details/%s/' %id_commande)
            """else:
                return HttpResponseRedirect('/commandes/')"""
        except Exception as e:
            request.notifications.error(form.errors)
    else:
        form = CommandeForm(initial={'total':0,'autre1':0,'autre2':0,'autre3':0})            
        return render_to_response('commandes/form/form_commande.html',
                                    {'form': form,
                                     'titre':"Tạo đơn hàng mới!",
                                      'url': '/commandes/addcommande/'},
                                      context_instance = RequestContext(request))